<template>
<div style="padding:6px;">
    <el-card v-show="showSearch" style="margin-bottom:6px;">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" style="margin-bottom:-20px;">
            <el-form-item label="场景名称" prop="sceneName">
                <el-input v-model="queryParams.sceneName" placeholder="请输入场景名称" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
            <el-form-item style="float:right;">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['iot:scene:add']">新增</el-button>
            </el-form-item>
        </el-form>
    </el-card>

    <el-card style="padding-bottom:100px;">
        <el-table v-loading="loading" :data="sceneList" @selection-change="handleSelectionChange" border>
            <el-table-column label="场景名称" align="center" prop="sceneName" />
            <el-table-column label="状态" align="center" prop="status" width="120">
                <template slot-scope="scope">
                    <el-tag type="success" size="small" v-if="scope.row.status==1">启动</el-tag>
                    <el-tag type="danger" size="small" v-if="scope.row.status==2">暂停</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="触发器" align="left" header-align="center" prop="triggers" min-width="120">
                <template slot-scope="scope">
                    <div v-html="formatTriggersDisplay(scope.row.triggers)"></div>
                </template>
            </el-table-column>
            <el-table-column label="执行动作" align="left" header-align="center" prop="actions" min-width="100">
                <template slot-scope="scope">
                    <div v-html="formatActionsDisplay(scope.row.actions)"></div>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="120">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view" @click="handleUpdate(scope.row)" v-hasPermi="['iot:scene:add']">查看</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:scene:remove']">删除</el-button>
                    <el-button size="mini" type="text" icon="el-icon-caret-right" @click="handleRun(scope.row)" v-hasPermi="['iot:scene:edit']" style="margin-right:40px;">执行一次</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改场景联动对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
            <div class="el-divider el-divider--horizontal" style="margin-top: -25px;"></div>
            <el-form ref="form" :model="form" :rules="rules" label-width="90px">
                <el-row :gutter="50">
                    <el-col :span="12">
                        <el-form-item label="场景名称" prop="sceneName">
                            <el-input v-model="form.sceneName" placeholder="请输入场景名称" />
                        </el-form-item>
                        <el-form-item label="场景状态">
                            <el-switch v-model="form.status" :active-value="1" :inactive-value="2" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注信息" prop="remark">
                            <el-input v-model="form.remark" type="textarea" rows="4" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <div style="height:1px;background-color:#ddd;margin:0 0 20px 0;"></div>
                <el-form-item label="" prop="triggers">
                    <el-tooltip class="item" effect="dark" content="满足任意一个条件触发" placement="right-start" slot="label">
                        <span>触发器 <i class="el-icon-question"></i></span>
                    </el-tooltip>
                    <div v-for="(item,index) in formJson.triggers" :key="index" style="margin-bottom:15px;padding:10px;background-color:#f8f8f8;border-radius:5px;">
                        <el-row style="margin-bottom:5px;">
                            <el-col :span="4">
                                <el-select v-model="item.source" placeholder="请选择" size="small" @change="changeTriggerSource($event,index)">
                                    <el-option v-for="subItem in triggerSource" :key="subItem.value" :label="subItem.label" :value="subItem.value">
                                    </el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="10" :offset="1" v-if="item.source==1">
                                <el-input readonly v-model="item.deviceName" size="small" placeholder="请选择设备" style="margin-top:3px;">
                                    <el-button slot="append" @click="selectDevice('trigger',item.deviceId,index)" size="small">选择</el-button>
                                </el-input>
                            </el-col>
                            <el-col :span="2" :offset="item.source==1?7:18" v-if="index!=0">
                                <el-button size="small" plain type="danger" style="padding:5px;" icon="el-icon-delete" @click="removeTriggerItem(index)">删除</el-button>
                            </el-col>
                        </el-row>

                        <!--定时-->
                        <el-row v-if="item.source==2">
                            <el-col :span="4">
                                <el-time-picker style="width:100%;" v-model="item.timerTimeValue" size="small" value-format="HH:mm" format="HH:mm" placeholder="选择时间" @change="timeChange($event,index)" :disabled="item.isAdvance==1"></el-time-picker>
                            </el-col>
                            <el-col :span="19" :offset="1">
                                <el-select v-model="item.timerWeekValue" placeholder="请选择" multiple style="width:100%;" @change="weekChange($event,index)" size="small" :disabled="item.isAdvance==1">
                                    <el-option v-for="subItem in timerWeeks" :key="subItem.value" :label="subItem.label" :value="subItem.value">
                                    </el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="4" style="margin-top:5px;">
                                <el-checkbox v-model="item.isAdvance" :true-label="1" :false-label="0" @change="customerCronChange(($event,index))" border size="small" style="width:100%;">自定义CRON</el-checkbox>
                            </el-col>
                            <el-col :span="19" :offset="1" style="margin-top:10px;">
                                <el-input v-model="item.cronExpression" placeholder="cron执行表达式" :disabled="item.isAdvance==0" size="small">
                                    <template slot="append">
                                        <el-button type="primary" @click="handleShowCron(item,index)" :disabled="item.isAdvance==0">
                                            生成表达式
                                            <i class="el-icon-time el-icon--right"></i>
                                        </el-button>
                                    </template>
                                </el-input>
                            </el-col>
                        </el-row>
                        <!--设备-->
                        <el-row v-if="item.thingsModel">
                            <el-col :span="4">
                                <el-select v-model="item.type" placeholder="请选择" size="small" @change="triggerTypeChange($event,index)">
                                    <el-option v-for="(subItem,subIndex) in triggerTypes" :key="subIndex+'type'" :label="subItem.label" :value="subItem.value">
                                    </el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="5" :offset="1">
                                <el-select v-model="item.id" placeholder="请选择" size="small" v-if="item.type==1" @change="thingsModelTriggerItemChange($event,index)">
                                    <el-option v-for="(subItem,subIndex) in item.thingsModel.properties" :key="subIndex+'triggerProperty'" :label="subItem.name" :value="subItem.id">
                                    </el-option>
                                </el-select>
                                <el-select v-model="item.id" placeholder="请选择" size="small" v-else-if="item.type==2" @change="thingsModelTriggerItemChange($event,index)">
                                    <el-option v-for="(subItem,subIndex) in item.thingsModel.functions" :key="subIndex+'triggerFunc'" :label="subItem.name" :value="subItem.id">
                                    </el-option>
                                </el-select>
                                <el-select v-model="item.id" placeholder="请选择" size="small" v-else-if="item.type==3" @change="thingsModelTriggerItemChange($event,index)">
                                    <el-option v-for="(subItem,subIndex) in item.thingsModel.events" :key="subIndex+'triggerEvents'" :label="subItem.name" :value="subItem.id">
                                    </el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="4" :offset="1">
                                <el-select v-model="item.operator" placeholder="请选择操作符" size="small" v-if="item.type==1 || item.type==2 || item.type==3">
                                    <el-option key="=" label="等于（=）" value="=" />
                                    <el-option key="!=" label="不等于（!=）" value="!=" />
                                    <el-option key=">" label="大于（>）" value=">" />
                                    <el-option key="<" label="小于（<）" value="<" />
                                    <el-option key=">=" label="大于等于（>=）" value=">=" />
                                    <el-option key="<=" label="小于等于（<=）" value="<=" />
                                    <el-option key="contain" label="包含（contain）" value="contain" />
                                    <el-option key="notcontain" label="不包含（not contain）" value="notcontain" />
                                </el-select>
                            </el-col>
                            <el-col :span="8" :offset="1" v-if="item.type==1 || item.type==2 || item.type==3">
                                <span v-if="item.thingsModelItem &&(item.thingsModelItem.datatype.type=='integer' || item.thingsModelItem.datatype.type=='decimal')">
                                    <el-input v-model="item.value" placeholder="值" :max="item.thingsModelItem.datatype.max" :min="item.thingsModelItem.datatype.min" type="number" size="small">
                                        <template slot="append">{{item.thingsModelItem.datatype.unit}}</template>
                                    </el-input>
                                </span>
                                <span v-else-if=" item.thingsModelItem && item.thingsModelItem.datatype.type=='bool'">
                                    <el-switch v-model="item.value" :active-text="item.thingsModelItem.datatype.trueText" :inactive-text="item.thingsModelItem.datatype.falseText" active-value="1" inactive-value="0">
                                    </el-switch>
                                </span>
                                <span v-else-if="item.thingsModelItem && item.thingsModelItem.datatype.type=='enum'">
                                    <el-select v-model="item.value" placeholder="请选择" style="width:100%" size="small">
                                        <el-option v-for="(subItem,subIndex) in item.thingsModelItem.datatype.enumList" :key="subIndex+'things'" :label="subItem.text" :value="subItem.value">
                                        </el-option>
                                    </el-select>
                                </span>
                                <span v-else-if="item.thingsModelItem && item.thingsModelItem.datatype.type=='string'">
                                    <el-input v-model="item.value" placeholder="请输入字符串" :max="item.thingsModelItem.datatype.maxLength" />
                                </span>
                                <span v-else-if="item.thingsModelItem && item.thingsModelItem.datatype.type=='array'">
                                    <el-input v-model="item.value" placeholder="请输入英文逗号分隔的数组" />
                                </span>
                            </el-col>
                        </el-row>
                    </div>
                    <div>+ <a style="color:#409EFF" @click="addTriggerItem()">添加触发器</a></div>
                </el-form-item>

                <el-divider></el-divider>
                <el-form-item label="执行动作">
                    <div v-for="(item,index) in formJson.actions" :key="index" style="margin-bottom:15px;padding:10px;background-color:#f8f8f8;border-radius:5px;">
                        <el-row style="margin-bottom:10px;">
                            <el-col :span="10">
                                <el-input readonly v-model="item.deviceName" size="small" placeholder="请选择设备" style="margin-top:3px;">
                                    <el-button slot="append" @click="selectDevice('action',item.deviceId,index)" size="small">选择</el-button>
                                </el-input>
                            </el-col>
                            <el-col :span="2" :offset="12">
                                <el-button size="small" v-if="index!=0" plain type="danger" style="padding:5px;" icon="el-icon-delete" @click="removeActionItem(index)">删除</el-button>
                            </el-col>
                        </el-row>
                        <el-row v-if="item.thingsModel">
                            <el-col :span="4">
                                <el-select v-model="item.type" placeholder="请选择" size="small" @change="actionTypeChange($event,index)">
                                    <el-option v-for="(subItem,subIndex) in actionTypes" :key="subIndex+'type'" :label="subItem.label" :value="subItem.value">
                                    </el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="5" :offset="1">
                                <el-select v-model="item.id" placeholder="请选择" v-if="item.type==1" size="small" @change="thingsModelActionItemChange($event,index)">
                                    <el-option v-for="(subItem,subIndex) in item.thingsModel.propertiesExceptMonitor" :key="subIndex+'actionProperty'" :label="subItem.name" :value="subItem.id">
                                    </el-option>
                                </el-select>
                                <el-select v-model="item.id" placeholder="请选择" v-else-if="item.type==2" size="small" @change="thingsModelActionItemChange($event,index)">
                                    <el-option v-for="(subItem,subIndex) in item.thingsModel.functions" :key="subIndex+'actionFunc'" :label="subItem.name" :value="subItem.id">
                                    </el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="10" :offset="1">
                                <!--物模型项的值-->
                                <span v-if="item.thingsModelItem &&(item.thingsModelItem.datatype.type=='integer' || item.thingsModelItem.datatype.type=='decimal')">
                                    <el-input v-model="item.value" placeholder="值" :max="item.thingsModelItem.datatype.max" :min="item.thingsModelItem.datatype.min" type="number" size="small">
                                        <template slot="append">{{item.thingsModelItem.datatype.unit}}</template>
                                    </el-input>
                                </span>
                                <span v-else-if=" item.thingsModelItem && item.thingsModelItem.datatype.type=='bool'">
                                    <el-switch v-model="item.value" :active-text="item.thingsModelItem.datatype.trueText" :inactive-text="item.thingsModelItem.datatype.falseText" active-value="1" inactive-value="0">
                                    </el-switch>
                                </span>
                                <span v-else-if="item.thingsModelItem && item.thingsModelItem.datatype.type=='enum'">
                                    <el-select v-model="item.value" placeholder="请选择" style="width:100%" size="small">
                                        <el-option v-for="(subItem,subIndex) in item.thingsModelItem.datatype.enumList" :key="subIndex+'things'" :label="subItem.text" :value="subItem.value">
                                        </el-option>
                                    </el-select>
                                </span>
                                <span v-else-if="item.thingsModelItem && item.thingsModelItem.datatype.type=='string'">
                                    <el-input v-model="item.value" placeholder="请输入字符串" :max="item.thingsModelItem.datatype.maxLength" />
                                </span>
                                <span v-else-if="item.thingsModelItem && item.thingsModelItem.datatype.type=='array'">
                                    <el-input v-model="item.value" placeholder="请输入英文逗号分隔的数组" />
                                </span>
                            </el-col>
                        </el-row>
                    </div>
                    <div>+ <a style="color:#409EFF" @click="addActionItem()">添加执行动作</a></div>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" :disabled="updateBtnDisabled" :loading="confirmLoading" v-hasPermi="['iot:scene:edit']" v-show="form.sceneId">修 改</el-button>
                <el-button type="primary" @click="submitForm" :disabled="updateBtnDisabled" :loading="confirmLoading" v-hasPermi="['iot:scene:add']" v-show="!form.sceneId">新 增</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 设备列表 -->
        <deviceList ref="deviceList" @deviceEvent="getSelectDevice($event)"></deviceList>
    </el-card>

    <!-- CRON表达式生成器 -->
    <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
        <crontab @hide="openCron=false" @fill="crontabFill" :expression="expression" style="padding-bottom:80px;"></crontab>
    </el-dialog>

</div>
</template>

<script>
import {
    listScene,
    getScene,
    delScene,
    addScene,
    updateScene
} from "@/api/iot/scene";
import {
    cacheJsonThingsModel
} from "@/api/iot/model";
import Crontab from '@/components/Crontab'
import deviceList from "./device-list"

export default {
    name: "scene",
    components: {
        deviceList,
        Crontab
    },
    data() {
        return {
            // 确认按钮加载
            confirmLoading:false,
            // 更新按钮
            updateBtnDisabled: true,
            // 当前选择设备时的类型（trigger/action）
            currentType: null,
            // 当前选择设备时的类型索引
            currentIndex: null,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 场景联动表格数据
            sceneList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否显示Cron表达式弹出层
            openCron: false,
            // 传入的表达式
            expression: "",
            // 触发器的索引，用于接收传入的表达式
            triggerIndex: 0,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                sceneName: null,
                userId: null,
                userName: null,
            },
            timerWeeks: [{
                value: 1,
                label: '周一'
            }, {
                value: 2,
                label: '周二'
            }, {
                value: 3,
                label: '周三'
            }, {
                value: 4,
                label: '周四'
            }, {
                value: 5,
                label: '周五'
            }, {
                value: 6,
                label: '周六'
            }, {
                value: 7,
                label: '周日'
            }],
            // 触发器源 1=设备，2=定时
            triggerSource: [{
                value: 1,
                label: '设备触发'
            }, {
                value: 2,
                label: '定时触发'
            }],
            // 触发器类别
            triggerTypes: [{
                    value: 1,
                    label: '属性'
                }, {
                    value: 2,
                    label: '功能'
                }, {
                    value: 3,
                    label: '事件'
                },
                // {
                //     value: 4,
                //     label: '设备升级'
                // },
                {
                    value: 5,
                    label: '设备上线'
                }, {
                    value: 6,
                    label: '设备下线'
                }
            ],
            // 动作类别
            actionTypes: [{
                value: 1,
                label: '属性'
            }, {
                value: 2,
                label: '功能'
            }],
            // 表单参数
            formJson: {
                triggers: [{
                    // 时间
                    timerTimeValue: '',
                    // 星期
                    timerWeekValue: [1, 2, 3, 4, 5, 6, 7],
                }],
                actions: [],
            },
            form: {},
            // 表单校验
            rules: {
                sceneName: [{
                    required: true,
                    message: "场景名称不能为空",
                    trigger: "blur"
                }],
                userId: [{
                    required: true,
                    message: "用户ID不能为空",
                    trigger: "blur"
                }],
                userName: [{
                    required: true,
                    message: "用户名称不能为空",
                    trigger: "blur"
                }],
            }
        };
    },
    created() {
        this.connectMqtt();
        this.getList();
    },
    methods: {
        /* 连接Mqtt消息服务器 */
        async connectMqtt() {
            if (this.$mqttTool.client == null) {
                await this.$mqttTool.connect();
            }
        },

        /** 查询场景联动列表 */
        getList() {
            this.loading = true;
            listScene(this.queryParams).then(response => {
                this.sceneList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                sceneId: null,
                sceneName: null,
                userId: null,
                userName: null,
                remark: null,
                status: 1,
            };
            this.formJson = {
                triggers: [{
                    id: "",
                    name: "",
                    value: "",
                    type: 1,
                    deviceId: 0,
                    deviceName: "",
                    productId: 0,
                    productName: "",
                    source: 1, //1=设备，2=定时
                    modelType: 1, // 1=属性，2=功能
                    jobId: 0,
                    cronExpression: "",
                    isAdvance: 0,
                    operator: "=",
                    // 时间
                    timerTimeValue: '',
                    // 星期
                    timerWeekValue: [1, 2, 3, 4, 5, 6, 7],
                    // 物模型
                    // thingsModel: {
                    //     properties: [],
                    //     events: [],
                    //     functions: []
                    // }
                }],
                actions: [{
                    id: "",
                    name: "",
                    value: "",
                    type: 2, // 1=属性，2=功能，3=事件，5=设备上线，6=设备下线
                }],
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.sceneId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.updateBtnDisabled = false;
            this.open = true;
            this.title = "添加场景联动";
        },
        /** 执行一次 */
        handleRun(scene) {
            let actions = JSON.parse(scene.actions);
            console.log(actions);
            for (let i = 0; i < actions.length; i++) {
                let topic = "";
                let message = ""
                if (actions[i].type == 1) {
                    // 属性,在线模式
                    topic = "/" + actions[i].productId + "/" + actions[i].serialNumber + "/property-online/get";
                    message = '[{"id":"' + actions[i].id + '","value":"' + actions[i].value + '"}]';
                } else if (actions[i].type == 2) {
                    // 功能,在线模式
                    topic = "/" + actions[i].productId + "/" + actions[i].serialNumber + "/function-online/get";
                    message = '[{"id":"' + actions[i].id + '","value":"' + actions[i].value + '"}]';
                }
                if (topic != "") {
                    // 发布
                    this.$mqttTool.publish(topic, message, actions[i].deviceName).then(res => {
                        this.$modal.notifySuccess(res);
                    }).catch(res => {
                        this.$modal.notifyError(res);
                    });
                }
            }

        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.updateBtnDisabled = true;
            const sceneId = row.sceneId || this.ids
            getScene(sceneId).then(response => {
                this.form = response.data;
                // triggers赋值
                this.formJson.triggers = JSON.parse(this.form.triggers);
                for (let i = 0; i < this.formJson.triggers.length; i++) {
                    // 定时
                    if (this.formJson.triggers[i].source == 2) {
                        if (this.formJson.triggers[i].isAdvance == 0) {
                            let arrayValue = this.formJson.triggers[i].cronExpression.substring(12).split(",").map(Number);
                            this.formJson.triggers[i].timerWeekValue = arrayValue;
                            let timerTimeValue = this.formJson.triggers[i].cronExpression.substring(5, 7) + ":" + this.formJson.triggers[i].cronExpression.substring(2, 4);
                            // 解决时间选择器不能编辑问题
                            this.$set(this.formJson.triggers[i], 'timerTimeValue', timerTimeValue);
                        }
                    } else if (this.formJson.triggers[i].source == 1) {
                        // 获取设备和物模型详情
                        this.getDevice(this.formJson.triggers[i], i, 'trigger');
                    }
                }
                // actions赋值
                this.formJson.actions = JSON.parse(this.form.actions);
                for (let i = 0; i < this.formJson.actions.length; i++) {
                    // 获取设备和物模型详情
                    this.getDevice(this.formJson.actions[i], i, 'action');
                }
                // 按钮可用
                setTimeout(() => {
                    this.updateBtnDisabled = false;
                }, 2000)
                this.open = true;
                this.title = "修改场景联动";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    // 触发器验证
                    for (let i = 0; i < this.formJson.triggers.length; i++) {
                        // 设备升级、上线、下线
                        if (this.formJson.triggers[i].type == 4 || this.formJson.triggers[i].type == 5 || this.formJson.triggers[i].type == 6) {
                            continue;
                        }
                        // 值不能为空
                        if (this.formJson.triggers[i].source == 1) {
                            if (this.formJson.triggers[i].id == "" || this.formJson.triggers[i].name == "" || this.formJson.triggers[i].value == "") {
                                this.$modal.alertError("触发器中的选项和值不能为空");
                                return;
                            }
                        }
                        // 定时时间不能为空
                        if (this.formJson.triggers[i].source == 2) {
                            if (this.formJson.triggers[i].isAdvance == 0) {
                                if (this.formJson.triggers[i].timerTimeValue == "" || this.formJson.triggers[i].timerTimeValue == null) {
                                    this.$modal.alertError("执行时间不能空");
                                    return;
                                }
                                if (this.formJson.triggers[i].timerWeekValue == null || this.formJson.triggers[i].timerWeekValue == "") {
                                    this.$modal.alertError("请选择要执行的星期");
                                    return;
                                }
                            } else if (this.formJson.triggers[i].isAdvance == 1) {
                                if (this.formJson.triggers[i].cronExpression == "") {
                                    this.$modal.alertError("cron表达式不能为空");
                                    return;
                                }
                            }
                        }
                        // 清空不需要提交数据
                        delete this.formJson.triggers[i].thingsModelItem;
                        delete this.formJson.triggers[i].thingsModel;
                        delete this.formJson.triggers[i].timerTimeValue;
                        delete this.formJson.triggers[i].timerWeekValue;
                        delete this.formJson.triggers[i].timerWeekRepeatValue;
                    }
                    // 动作验证
                    for (let i = 0; i < this.formJson.actions.length; i++) {
                        if (this.formJson.actions[i].id == "" || this.formJson.actions[i].name == "" || this.formJson.actions[i].value == "") {
                            this.$modal.alertError("执行动作中的选项和值不能为空");
                            return;
                        }
                        // 清空不需要提交数据
                        delete this.formJson.actions[i].thingsModelItem;
                        delete this.formJson.actions[i].thingsModel;
                    }
                    this.form.userId = 1;
                    this.form.userName = "admin";
                    this.form.triggers = JSON.stringify(this.formJson.triggers);
                    this.form.actions = JSON.stringify(this.formJson.actions);
                    this.confirmLoading=true;
                    if (this.form.sceneId != null) {
                        updateScene(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.confirmLoading=false;
                            this.getList();
                        });
                    } else {
                        addScene(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.confirmLoading=false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const sceneIds = row.sceneId || this.ids;
            this.$modal.confirm('是否确认删除场景联动编号为"' + sceneIds + '"的数据项？').then(function () {
                return delScene(sceneIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('iot/scene/export', {
                ...this.queryParams
            }, `scene_${new Date().getTime()}.xlsx`)
        },
        /** 添加动作 */
        addActionItem() {
            this.formJson.actions.push({
                id: "",
                name: "",
                value: "",
                type: 2,
                deviceId: 0,
                deviceName: "",
                productId: 1,
                productName: "",
                // thingsModel: {
                //     properties: [],
                //     functions: [],
                //     events: []
                // }
            })
        },
        /** 删除动作 */
        removeActionItem(index) {
            this.formJson.actions.splice(index, 1);
        },
        /** 触发器源改变事件 **/
        changeTriggerSource(source, index) {
            // 1=设备，2=定时
            if (source == 2) {
                this.formJson.triggers[index].deviceId = 0;
                this.formJson.triggers[index].deviceName = '';
                this.formJson.triggers[index].productId = 0;
                this.formJson.triggers[index].productName = '';
                this.formJson.triggers[index].serialNumber = '';
                this.formJson.triggers[index].id = '';
                this.formJson.triggers[index].name = '';
                this.formJson.triggers[index].value = '';
                this.formJson.triggers[index].thingsModelItem = null;
                this.formJson.triggers[index].thingsModel = null;
                this.formJson.triggers[index].operator = "";
                // 时间
                this.formJson.triggers[index].timerTimeValue = '';
                // 星期
                this.formJson.triggers[index].timerWeekValue = [1, 2, 3, 4, 5, 6, 7];
            }
        },
        /** 添加触发器 */
        addTriggerItem() {
            this.formJson.triggers.push({
                id: "",
                name: "",
                value: "",
                type: 1,
                deviceId: 0,
                deviceName: "",
                serialNumber: null,
                productId: 0,
                productName: "",
                source: 1, //1=设备，2=定时
                jobId: 0,
                cronExpression: "",
                isAdvance: 0,
                operator: "=",
                // 时间
                timerTimeValue: '',
                // 星期
                timerWeekValue: [1, 2, 3, 4, 5, 6, 7],
                // 物模型
                // thingsModel: {
                //     properties: [],
                //     functions: [],
                //     events: []
                // }
            })
        },
        /** 删除触发器 */
        removeTriggerItem(index) {
            this.formJson.triggers.splice(index, 1);
        },
        /** cron表达式按钮操作 */
        handleShowCron(item, index) {
            this.expression = item.cronExpression;
            this.triggerIndex = index;
            this.openCron = true;
        },
        /** 确定后回传值 */
        crontabFill(value) {
            this.formJson.triggers[this.triggerIndex].cronExpression = value;
        },
        /** 星期改变事件 **/
        weekChange(data, index) {
            this.gentCronExpression(index);
        },
        /** 时间改变事件 **/
        timeChange(data, index) {
            console.log('时间改变了', data);
            this.gentCronExpression(index);
        },
        /**自定义cron表达式选项改变事件 */
        customerCronChange(data, index) {
        },
        /** 生成cron表达式**/
        gentCronExpression(index) {
            let hour = "00";
            let minute = "00";
            if (this.formJson.triggers[index].timerTimeValue != null && this.formJson.triggers[index].timerTimeValue != "") {
                hour = this.formJson.triggers[index].timerTimeValue.substring(0, 2);
                minute = this.formJson.triggers[index].timerTimeValue.substring(3);
            }
            let week = "*";
            if (this.formJson.triggers[index].timerWeekValue.length > 0) {
                week = this.formJson.triggers[index].timerWeekValue.sort();
            }
            this.formJson.triggers[index].cronExpression = "0 " + minute + " " + hour + " ? * " + week;
        },
        /** 触发器类型改变事件 **/
        triggerTypeChange(source, index) {
            this.formJson.triggers[index].id = '';
            this.formJson.triggers[index].name = '';
            this.formJson.triggers[index].value = '';
            this.formJson.triggers[index].thingsModelItem = null;
            this.formJson.triggers[index].operator = "=";
        },
        /** 触发器物模型项改变事件 **/
        thingsModelTriggerItemChange(identifier, index) {
            this.formJson.triggers[index].value = "";
            if (this.formJson.triggers[index].type == 1) {
                //属性
                for (let i = 0; i < this.formJson.triggers[index].thingsModel.properties.length; i++) {
                    if (this.formJson.triggers[index].thingsModel.properties[i].id == identifier) {
                        this.formJson.triggers[index].name = this.formJson.triggers[index].thingsModel.properties[i].name;
                        this.formJson.triggers[index].thingsModelItem = this.formJson.triggers[index].thingsModel.properties[i];
                        break;
                    }
                }
            } else if (this.formJson.triggers[index].type == 2) {
                //功能
                for (let i = 0; i < this.formJson.triggers[index].thingsModel.functions.length; i++) {
                    if (this.formJson.triggers[index].thingsModel.functions[i].id == identifier) {
                        this.formJson.triggers[index].name = this.formJson.triggers[index].thingsModel.functions[i].name;
                        this.formJson.triggers[index].thingsModelItem = this.formJson.triggers[index].thingsModel.functions[i];
                        break;
                    }
                }
            } else if (this.formJson.triggers[index].type == 3) {
                //功能
                for (let i = 0; i < this.formJson.triggers[index].thingsModel.events.length; i++) {
                    if (this.formJson.triggers[index].thingsModel.events[i].id == identifier) {
                        this.formJson.triggers[index].name = this.formJson.triggers[index].thingsModel.events[i].name;
                        this.formJson.triggers[index].thingsModelItem = this.formJson.triggers[index].thingsModel.events[i];
                        break;
                    }
                }
            }
        },
        /** 动作类型改变事件 **/
        actionTypeChange(data, index) {
            this.formJson.actions[index].id = null;
            this.formJson.actions[index].value = null;
            this.formJson.actions[index].thingsModelItem = null;
        },
        /** 动作物模型项改变事件 **/
        thingsModelActionItemChange(identifier, index) {
            this.formJson.actions[index].value = "";
            if (this.formJson.actions[index].type == 1) {
                //属性
                for (let i = 0; i < this.formJson.actions[index].thingsModel.properties.length; i++) {
                    if (this.formJson.actions[index].thingsModel.properties[i].id == identifier) {
                        this.formJson.actions[index].name = this.formJson.actions[index].thingsModel.properties[i].name;
                        this.formJson.actions[index].thingsModelItem = this.formJson.actions[index].thingsModel.properties[i];
                        break;
                    }
                }
            } else if (this.formJson.actions[index].type == 2) {
                //功能
                for (let i = 0; i < this.formJson.actions[index].thingsModel.functions.length; i++) {
                    if (this.formJson.actions[index].thingsModel.functions[i].id == identifier) {
                        this.formJson.actions[index].name = this.formJson.actions[index].thingsModel.functions[i].name;
                        this.formJson.actions[index].thingsModelItem = this.formJson.actions[index].thingsModel.functions[i];
                        break;
                    }
                }
            }
        },
        /**
         * 获取设备和物模型详情
         * Json:触发器或动作
         * index：索引
         * type：类型：触发器或动作
         */
        getDevice(json, index, type) {
            if (type == 'action') {
                // 获取物模型
                cacheJsonThingsModel(json.productId).then(response => {
                    this.formJson.actions[index].thingsModel = JSON.parse(response.data);
                    // 过滤监测数据，监测数据为只读
                    this.formJson.actions[index].thingsModel.propertiesExceptMonitor = this.formJson.actions[index].thingsModel.properties.filter(item => item.isMonitor == 0);
                    if (this.formJson.actions[index].type == 1) {
                        for (let j = 0; j < this.formJson.actions[index].thingsModel.properties.length; j++) {
                            if (this.formJson.actions[index].id == this.formJson.actions[index].thingsModel.properties[j].id) {
                                this.formJson.actions[index].thingsModelItem = this.formJson.actions[index].thingsModel.properties[j];
                                break;
                            }
                        }
                    } else if (this.formJson.actions[index].type == 2) {
                        for (let j = 0; j < this.formJson.actions[index].thingsModel.functions.length; j++) {
                            if (this.formJson.actions[index].id == this.formJson.actions[index].thingsModel.functions[j].id) {
                                this.formJson.actions[index].thingsModelItem = this.formJson.actions[index].thingsModel.functions[j];
                                break;
                            }
                        }
                    }
                    // 解决数组在界面中不更新问题
                    this.$set(this.formJson.actions, index, this.formJson.actions[index]);
                });
            } else if (type == 'trigger') {
                // 获取物模型
                cacheJsonThingsModel(json.productId).then(response => {
                    this.formJson.triggers[index].thingsModel = JSON.parse(response.data);
                    // 过滤监测数据，监测数据为只读
                    this.formJson.triggers[index].thingsModel.propertiesExceptMonitor = this.formJson.triggers[index].thingsModel.properties.filter(item => item.isMonitor == 0);
                    if (this.formJson.triggers[index].type == 1) {
                        for (let j = 0; j < this.formJson.triggers[index].thingsModel.properties.length; j++) {
                            if (this.formJson.triggers[index].id == this.formJson.triggers[index].thingsModel.properties[j].id) {
                                this.formJson.triggers[index].thingsModelItem = this.formJson.triggers[index].thingsModel.properties[j];
                                break;
                            }
                        }
                    } else if (this.formJson.triggers[index].type == 2) {
                        for (let j = 0; j < this.formJson.triggers[index].thingsModel.functions.length; j++) {
                            if (this.formJson.triggers[index].id == this.formJson.triggers[index].thingsModel.functions[j].id) {
                                this.formJson.triggers[index].thingsModelItem = this.formJson.triggers[index].thingsModel.functions[j];
                                break;
                            }
                        }
                    } else if (this.formJson.triggers[index].type == 3) {
                        for (let j = 0; j < this.formJson.triggers[index].thingsModel.events.length; j++) {
                            console.log(this.formJson.triggers[index].thingsModel);
                            if (this.formJson.triggers[index].id == this.formJson.triggers[index].thingsModel.events[j].id) {
                                this.formJson.triggers[index].thingsModelItem = this.formJson.triggers[index].thingsModel.events[j];
                                break;
                            }
                        }
                    }
                    // 解决数组在界面中不更新问题
                    this.$set(this.formJson.triggers, index, this.formJson.triggers[index]);
                });
            }
        },
        /* 选择设备
         *  type : 'trigger','action'
         */
        selectDevice(type, deviceId, index) {
            this.currentType = type;
            this.currentIndex = index;
            // 刷新子组件
            this.$refs.deviceList.openDeviceList = true;
            this.$refs.deviceList.getList(deviceId);
        },
        /**获取选中的设备 */
        getSelectDevice(device) {
            if (this.currentType == null) {
                return;
            }
            if (this.currentType == 'trigger') {
                this.formJson.triggers[this.currentIndex].deviceId = device.deviceId;
                this.formJson.triggers[this.currentIndex].deviceName = device.deviceName;
                this.formJson.triggers[this.currentIndex].serialNumber = device.serialNumber;
                this.formJson.triggers[this.currentIndex].productId = device.productId;
                this.formJson.triggers[this.currentIndex].productName = device.productName;
                // 获取物模型
                cacheJsonThingsModel(device.productId).then(response => {
                    this.formJson.triggers[this.currentIndex].thingsModel = JSON.parse(response.data);
                    // 过滤监测数据，监测数据为只读
                    this.formJson.triggers[this.currentIndex].thingsModel.propertiesExceptMonitor = this.formJson.triggers[this.currentIndex].thingsModel.properties.filter(item => item.isMonitor == 0);
                    this.formJson.triggers[this.currentIndex].id = null;
                    this.formJson.triggers[this.currentIndex].thingsModelItem = null;
                    this.formJson.triggers[this.currentIndex].value = '';
                    this.formJson.triggers[this.currentIndex].operator = "=";
                    // 解决数组在界面中不更新问题
                    this.$set(this.formJson.triggers, this.currentIndex, this.formJson.triggers[this.currentIndex]);
                });
            } else if (this.currentType == 'action') {
                this.formJson.actions[this.currentIndex].deviceId = device.deviceId;
                this.formJson.actions[this.currentIndex].deviceName = device.deviceName;
                this.formJson.actions[this.currentIndex].serialNumber = device.serialNumber;
                this.formJson.actions[this.currentIndex].productId = device.productId;
                this.formJson.actions[this.currentIndex].productName = device.productName;
                // 获取物模型
                cacheJsonThingsModel(device.productId).then(response => {
                    this.formJson.actions[this.currentIndex].thingsModel = JSON.parse(response.data);
                    // 过滤监测数据，监测数据为只读
                    this.formJson.actions[this.currentIndex].thingsModel.propertiesExceptMonitor = this.formJson.actions[this.currentIndex].thingsModel.properties.filter(item => item.isMonitor == 0);
                    this.formJson.actions[this.currentIndex].id = null;
                    this.formJson.actions[this.currentIndex].value = null;
                    this.formJson.actions[this.currentIndex].thingsModelItem = null;
                    // 解决数组在界面中不更新问题
                    this.$set(this.formJson.actions, this.currentIndex, this.formJson.actions[this.currentIndex]);
                });
            }
        },
        /** 格式化显示动作 */
        formatActionsDisplay(json) {
            if (json == null || json == "") {
                return;
            }
            let actions = JSON.parse(json);
            let result = "";
            for (let i = 0; i < actions.length; i++) {
                result = result + '<span style="font-weight:bold;margin-right:10px;">' + actions[i].deviceName + '</span>';
                result = result + actions[i].name + "值：<span style=\"color:#F56C6C\">" + actions[i].value + "</span><br />";
            }
            return result == "" ? "无" : result;
        },
        /** 格式化显示触发器 */
        formatTriggersDisplay(json) {
            if (json == null || json == "") {
                return;
            }
            let triggers = JSON.parse(json);
            let result = "";
            for (let i = 0; i < triggers.length; i++) {
                // 定时
                if (triggers[i].source == 2) {
                    result = result + '<span style="font-weight:bold;margin-right:10px;">定时触发</span>';
                    result = result + '<span style="color:#F56C6C"> ' + triggers[i].cronExpression + "</span><br />";
                    continue;
                }
                result = result + '<span style="font-weight:bold;margin-right:10px;">' + triggers[i].deviceName + '</span>';
                if (triggers[i].type == 1 || triggers[i].type == 2 || triggers[i].type == 3) {
                    result = result + triggers[i].name + " <span style=\"color:#F56C6C\">" + triggers[i].operator + " " + triggers[i].value + "</span><br />";
                } else if (triggers[i].type == 4) {
                    // 设备升级
                    result = result + "<span style=\"color:#F56C6C\">设备升级</span><br />";
                } else if (triggers[i].type == 5) {
                    // 设备上线
                    result = result + "<span style=\"color:#F56C6C\">设备上线</span><br />";
                } else if (triggers[i].type == 6) {
                    // 设备下线
                    result = result + "<span style=\"color:#F56C6C\">设备下线</span><br />";
                }

            }
            return result;
        },
    }
};
</script>
